#coding=utf-8
import requests
from bs4 import BeautifulSoup
user='admin'
pwd='password'
cookies=' '
def getToken():
    global cookies
    '''获取必须的token值'''
    url = 'http://localhost/login.php'
    r = requests.get(url=url)
    soup = BeautifulSoup(r.content, 'lxml')
    res = str(soup.find_all(name='input', attrs={'type': 'hidden'}))
    if 'Set-Cookie' in r.headers:
        sessionid = r.headers['Set-Cookie'][0:36]
        cookie = "security=low; " + sessionid
        cookies= cookie
    else:
        pass
    return res[-36:-4]
 
def getHeaders(cookie):
    '''构造包含phpsessionid的headers头信息'''
    global cookies
    headers = {
        'Host': 'localhost',
        'Content-Length': '89',
        'Origin': 'http://localhost',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://localhost/login.php',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'close'
        }
    headers['Cookie'] = cookie
    return headers
 
def httpLogin(user, pwd, token, session):
    '''登录请求，并相应location参数值'''
    headers = getHeaders(session)
    url = 'http://localhost/login.php'
    payload = {'username': user, 'password': pwd, 'Login': 'Login', 'user_token': token}
    req = requests.post(url=url, data=payload, allow_redirects=False,headers = headers)
    # 接下来需要判断302跳转到哪个页面
    addr = req.headers['Location']
    return addr
 
def main():
    token = getToken()
    addr = httpLogin(user, pwd, token, cookies)
    if addr == "login.php":
        print "账号：%s 密码:%s is error!" % (user,pwd)
    else:
        print "账号：%s 密码:%s is correct!" % (user,pwd)
    
 
if __name__ == '__main__':
    main()